import { _decorator, Button, Component, Node, tween, Tween, Vec3 } from 'cc';

const { ccclass, property, disallowMultiple, requireComponent } = _decorator;

@ccclass('Breath')
@disallowMultiple
@requireComponent(Button)
export class BtnBreathAnim extends Component {

    // 按钮原始缩放率
    private _originScale: Vec3;

    // 动画
    private _anim: Tween<Node> = null;

    // 按钮组件
    private get button(): Button {
        return this.node.getComponent(Button);
    }

    onLoad() {
        this._originScale = this.node.scale.clone();

        // 按钮点击缩放特效 与 所谓的呼吸缩放动画互相干扰, 需要特殊处理
        const btn = this.button;
        if (btn && btn.transition == Button.Transition.SCALE) {
            this.node.on(Node.EventType.TOUCH_START, this.stopAni, this);
            this.node.on(Node.EventType.TOUCH_END, this.playAnim, this);
            this.node.on(Node.EventType.TOUCH_CANCEL, this.playAnim, this);
        }
    }

    start() {
        this.playAnim();
    }

    onEnable() {
        this.playAnim();
    }

    public playAnim() {
        this.stopAni();

        const btn = this.button;
        if (!btn || !btn.interactable)
            return;

        // 循环缩放动画
        this._anim = tween(this.node)
            .repeatForever(
                tween(this.node)
                    .to(0.5, { scale: this._originScale.clone().multiplyScalar(1.2) }, { easing: 'sineOut' })
                    .to(0.5, { scale: this._originScale }, { easing: 'sineIn' })
                    .delay(0.2)
            )
            .start();
    }

    public stopAni() {
        if (this._anim) {
            this._anim.stop();
            this._anim = null;
            this.node.scale = this._originScale;
        }
    }

}

